package com.xxx.jdbc2;

import java.sql.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;

/**
 * @version v1.0
 * @Description:
 * @Author zhanzhongxin
 * @Date 2021/7/29 9:51
 * @Copyright 博为峰
 */

/*
   dao(Data Access Object) 数据访问对象

 */
public class JdbcDemo {
    public static void main(String[] args) {
//        final ArrayList<Student> list = query();
//        list.stream().forEach(System.out::println);
        final LocalDateTime now = LocalDateTime.now();
        final Student student = new Student(100, "岳云鹏2", 36, 170.36, "男", now, 2);
//        insert(student);
    }

//    private static void insert(Student student) {
//        String sql = "insert into stu(name,age,height,sex,birthday,cla_id)values (?, ?, ?, ?, ?, ?)";
//        try (final Connection connection = getConnection();
//             final PreparedStatement preparedStatement = connection.prepareStatement(sql);){
//            preparedStatement.setString(1, student.getName());
//            preparedStatement.setInt(2, student.getAge());
//            preparedStatement.setDouble(3, student.getHeight());
//            preparedStatement.setString(4, student.getSex());
//            //LocalDateTime -> Timestamp
//            preparedStatement.setTimestamp(5,student.getBirthday());
//            preparedStatement.setInt(6, student.getClaId());
//            preparedStatement.executeUpdate()
//        } catch (SQLException throwables) {
//            throwables.printStackTrace();
//        }
//    }


    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/j13", "root", "123456");
    }

    private static ArrayList<Student> query() {
        final ArrayList<Student> list = new ArrayList<>();
        try (final Connection connection = getConnection();
             final PreparedStatement preparedStatement = connection.prepareStatement("select * from stu");
             final ResultSet resultSet = preparedStatement.executeQuery();) {
            while (resultSet.next()) {
                final Student student = new Student();
                student.setId(resultSet.getInt("id"));
                student.setName(resultSet.getString("name"));
                student.setAge(resultSet.getInt("age"));
                student.setHeight(resultSet.getDouble("height"));
                final Timestamp birthday = resultSet.getTimestamp("birthday");
                final Instant instant = birthday.toInstant();
                final LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
                student.setBirthday(localDateTime);
                student.setClaId(resultSet.getInt("cla_id"));
                list.add(student);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
